package com.prawn.authority.service;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.prawn.authority.utils.IpAddressUtil;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service("captchaService")
public class CaptchaService {

	@Value("${captcha.timeout}")
	private Integer timeout;

	@Autowired
	private RedisTemplate redisTemplate;

	@Autowired
	private RabbitTemplate rabbitTemplate;

	@Autowired
	DefaultKaptcha producer;

	public Map<String, Object> generateVerificationCode(String ipAdrress) throws IOException {
		// 先删除redis中已有的验证码
		deleteVerificationCode(ipAdrress);
		Map<String, Object> map = new HashMap<>();
		// 生成文字验证码
		String text = producer.createText().toLowerCase();
		// 生成图片验证码
		BufferedImage image = producer.createImage(text);
		ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
		ImageIO.write(image, "jpg", outputStream);

		map.put("img", Base64.getEncoder().encodeToString(outputStream.toByteArray()));
		// 以ip为key  验证码为value存在redis中
		redisTemplate.opsForValue().set("verificationCode_ip_" + ipAdrress, text, timeout, TimeUnit.MINUTES);

		//将验证码以及邮箱发送到rabbitMQ中
//        rabbitTemplate.convertAndSend("captcha",map);

		return map;
	}

	public boolean deleteVerificationCode(String ipAddress){
		return redisTemplate.delete("verificationCode_ip_"+ipAddress);
	}

	public boolean checkVerificationCode(HttpServletRequest request, String userVerificationCode) {
		if (StringUtils.isEmpty(userVerificationCode)) {
			return false;
		}
		// 用户的ip地址
		String ipAdrress = IpAddressUtil.getIpAdrress(request);
		// 获取redis中的验证码
		String codeInRedis = (String) redisTemplate.opsForValue().get("verificationCode_ip_" + ipAdrress);
		// 删除redis中的验证码，使验证码具有一次性
		deleteVerificationCode(ipAdrress);
		return userVerificationCode.equalsIgnoreCase(codeInRedis);
	}
}
